#!/bin/sh

function readINI()
{
 FILENAME=$1; SECTION=$2; KEY=$3
 RESULT=`awk -F '=' '/\['$SECTION'\]/{a=1}a==1&&$1~/'$KEY'/{print $2;exit}' $FILENAME`
 echo $RESULT
}

if (${PRODUCTION}); then
    evnmode="production"
else
    evnmode="development"
fi
# debug log
# echo $evnmode

# set config path.
cfg_path="/app/config/cfg-"$evnmode".ini"
# debug log.
# echo $cfg_path

# create folders, chanage permission.
mkdir /app/static /app/uwsgi /app/uwsgi/logs /app/uwsgi/running /app/logs /app/config
cp -rf /app/make/inspection.json /app/config/inspection.json
cp -rf /app/make/regist_conf /app/config/regist_conf
cp -rf /app/make/cfg-example.ini $cfg_path
chmod 777 -R /app

# init configure.
sed -i 's!{rpc_service}!'$(readINI /app/make/docker_init.ini $evnmode RPC_SERVICE)'!g' $cfg_path \
&& sed -i 's/{mongodb_host}/'$(readINI /app/make/docker_init.ini $evnmode MONGO_DB_HOST)'/g' $cfg_path \
&& sed -i 's/{mysql_host}/'$(readINI /app/make/docker_init.ini $evnmode MYSQL_DB_HOST)'/g' $cfg_path \
&& sed -i 's/{service_host}/'$(readINI /app/make/docker_init.ini $evnmode SERVICE_HOST)'/g' $cfg_path \
&& sed -i 's/{service_port}/'$SERVICE_PORT'/g' $cfg_path \
&& sed -i 's/{service_db_name}/'$(readINI /app/make/docker_init.ini $evnmode DB_NAME)'/g' $cfg_path \
&& sed -i 's/{debug}/'$(readINI /app/make/docker_init.ini $evnmode DEBUG)'/g' $cfg_path
# debug log.

# init uwsgi config.
sed -i 's/{http_port}/'$SERVICE_PORT'/g' /app/make/uwsgi.example.ini \
&& cp -rf /app/make/uwsgi.example.ini /app/uwsgi.ini \
&& chmod 777 /app/uwsgi.ini
# debug log.
# cat /app/uwsgi.ini

# set apk source.
#sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories; \

#  copy start sh.
cp -rf /app/make/entrypoint.sh /app/entrypoint.sh \
&& chmod 777 /app/entrypoint.sh

# init django static.
pip install TDhelper --upgrade
python /app/manage.py collectstatic --noinput